// 配置
import Setting from '@/setting';
import Vue from 'vue';
const that = Vue.prototype;

/**
 * @param {* hasAuth } 当前按钮需要权限
 * @param {* authLabel } 当前按钮权限所需判断的名称，默认如果没有，就用按钮名称label判断
 * @param {* label } 当前按钮名称
*/
const getFilterListByCanShowBtn = (actionList, showBtn) => {
  if (!showBtn) { return actionList; } // 如果没有showBtn方法，默认都不需要权限判断
  return actionList.filter(
    item => (item.hasAuth && showBtn(item.authLabel || item.label)) || !item.hasAuth
  );
}

/* ----------------- tableBtns ---------------- */
/**
 * 获取一般按钮
 * @param { h } 要渲染的h函数
 * @param { item } 当前渲染按钮数据
*/
const getButton = (h, item) => {
  if (!item.method) { item.method = () => {}; } // 处理边界情况
  return <el-button
    type={ item.type || 'text' }
    size={ item.size }
    icon={item.icon}
    loading={item.loading}
    disabled={item.disabled}
    onClick={ () => { item.method() } }
  >{item.label}</el-button>
}
/**
 * 获取导入按钮
 * @param { h } 要渲染的h函数
 * @param { item } 当前渲染按钮数据
 * @param { data } 上传时附带的额外参数
 * @param { handleUploadSuccess } 导入成功回调方法
 * @param { handleUploadError } 导入错误回调方法
 * @param { handleBeforeUpload } 上传前回调方法
*/
const getImportButton = (h, item) => {
  if (item.showCondition === false) { return <span></span> }
  const buttonStyle = `margin: 0px 10px;`;
  const [ handleUploadSuccess, handleUploadError, handleBeforeUpload ] = getFinalMethods(item);
  const acceptFormats = item.accept || ['.xlsx', '.xls', '.csv'];
  return <el-upload
    data={item.data}
    style={buttonStyle}
    show-file-list={false}
    propsOnSuccess={(res) => { handleUploadSuccess(res) }}
    propsOnError={() => { handleUploadError() }}
    beforeUpload={file => handleBeforeUpload(file, acceptFormats)}
    accept={acceptFormats.join(', ')}
    action={`${Setting.uploadBaseURL}${item.action}`}
  >
    <el-button type="text" size={ item.size || 'large'} loading={item.loading}>模板导入</el-button>
  </el-upload>
}
/**
 * 获取最终处理后的上传方法
 * @param { methods } 上传方法对象集
 * @param { openLoading } 打开loading方法
 * @param { closeLoading } 关闭loading方法
*/
const getFinalMethods = (item) => {
  let { handleUploadSuccess, handleUploadError, handleBeforeUpload } = item.methods;
  const openLoading = () => { item.loadingFn(true); }
  const closeLoading = () => { item.loadingFn(false); }
  if (!handleUploadError) {
    handleUploadError = () => {
      closeLoading();
      that.$message.error('上传失败');
    }
  }
  const beforeUpload = (file) => {
    // 上传前进行格式校验
    const fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
    if (!['xlsx', 'xls', 'csv'].includes(fileType)) {
      that.$message.error('格式错误');
      return false;
    }
    if (handleBeforeUpload) {
      return handleBeforeUpload();
    }
    openLoading();
  }
  return [ handleUploadSuccess, handleUploadError, beforeUpload ];
}
/**
 * 获取按钮操作栏
 * @param { h } 要渲染的h函数
 * @param { list } 渲染按钮集合
 * @param { showBtn } 渲染权限判断方法
 * @param { position } 按钮栏位置，默认最后
 * list 定义方法
 list = [
    {
      label: '', // 按钮名
      method: '', // 按钮执行方法
      size: '', // 按钮大小
      icon: '', // 按钮icon
      loading, // 按钮loading
      disabled, // 按钮disabled
      hasNotAuth, // 此按钮是否需要判断权限（默认不传就判断）
    },
    { // 特殊导入按钮
      label: '',
      methods: {
        handleUploadSuccess, // 上传成功
        handleUploadError, // 上传失败
        handleBeforeUpload, // 上传之前
        handleUploadFormatError // 上传格式验证失败
      },
      type: 'import', // 声明此item是导入按钮
      action: '', // 上传路径（例如：sysback/update/product/structure/saveStructureToPage），开头一定不能加/
      closeLoading, // 上传关闭loading
      hasNotAuth, // 此按钮是否需要判断权限（默认不传就判断）
    },
    ...
  ]
*/
const getBtnsBar = (h, list, showBtn, position = 'end') => {
  const canShowList = getFilterListByCanShowBtn(list, showBtn);
  return <el-row type="flex" justify={position}>{
    canShowList.map(item => {
      if (item.type === 'import') {
        return getImportButton(h, item)
      }
      return getButton(h, item)
    })
  }</el-row>
}

const getTableHeadBtns = (h, list, showBtn) => {
  const canShowList = getFilterListByCanShowBtn(list, showBtn);
  const startBtns = canShowList.filter(item => !item.position);
  const endBtns = canShowList.filter(item => item.position === 'end');
  return <el-row type="flex" justify="space-between">
    <div>
      {
        startBtns.map(item => {
          if (item.type === 'import') {
            return getImportButton(h, item)
          }
          return getButton(h, item)
        })
      }
    </div>
    <div>
      {
        endBtns.map(item => {
          if (item.type === 'import') {
            return getImportButton(h, item)
          }
          return getButton(h, item)
        })
      }
    </div>
  </el-row>
}

/* ----------------- tableAction ---------------- */
// 超过两个数量
const isMoreThanTwoNum = (list) => {
  return list.length > 2;
}
// 获取渲染按钮
const getButtonRender = (h, row) => {
  return function (item) {
    return <el-button
      size={ item.size }
      type={ item.type || 'text' }
      onClick={() => item.method(row)}
    >{item.label}
    </el-button>;
  }
}
// 获取按钮集合
const getButtonsRender = (h, getButtonFn) => {
  return function (actionList) {
    return <div class="table-action">{
      actionList.map(item => { return getButtonFn(item); })
    }</div>;
  }
}
// 获取下拉按钮
const getDropdownRender = (h, actionList, getButtonFn) => {
  const dropdownLinkStyle = `cursor: pointer;
    color: #409EFF; font-size: 12px; font-weight: 500;`; // 下拉按钮样式
  const iconArrowDownStyle = `font-size: 12px;`; // 下拉
  const buttonPaddingStyle = `padding: 0 20px`;
  return <el-dropdown>
    <span style={dropdownLinkStyle}>
      更多<i class="el-icon-arrow-down" style={iconArrowDownStyle}></i>
    </span>
    <el-dropdown-menu slot="dropdown">
      { actionList.map(item => { return <div style={buttonPaddingStyle}>{getButtonFn(item)}</div> }) }
    </el-dropdown-menu>
  </el-dropdown>
}
/**
 * @param { h } 要渲染的h函数
 * @param { row } 当前操作表格行的row数据
 * @param { actionList } 要渲染的按钮列表集合
 * @param { isEnableDropdown } 是否启用多个按钮下拉模式，默认不启用
*/
const getTableAction = ({ h, row, actionList, showBtn }, isEnableDropdown = false) => {
  const getButtonFn = getButtonRender(h, row);
  const getButtonsFn = getButtonsRender(h, getButtonFn);
  const list = getFilterListByCanShowBtn(actionList, showBtn);
  if (isEnableDropdown && isMoreThanTwoNum(list)) {
    const cloneList = _.cloneDeep(list);
    const firstChild = cloneList.shift();
    return <el-row>
      { getButtonFn(firstChild) }
      <el-divider direction="vertical"></el-divider>
      { getDropdownRender(h, cloneList, getButtonFn) }
    </el-row>
  } else {
    return getButtonsFn(list);
  }
}
export {
  getBtnsBar,
  getTableAction,
  getTableHeadBtns
}
